package com.example.demo_text;

import user.User;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.*;

@WebServlet("/UpdateProfileServlet")
public class UpdateProfileServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        String email = request.getParameter("email");
        int age = Integer.parseInt(request.getParameter("age"));

        boolean success = UserDAO.updateUserProfile(user.getUsername(), email, age);

        if (success) {
            // 更新 session 中的 user 对象
            user.setEmail(email);
            user.setAge(age);
            session.setAttribute("user", user);
            response.sendRedirect("user_massage.jsp");
        } else {
            request.setAttribute("error", "更新失败，请稍后再试");
            request.getRequestDispatcher("user_massage_edit.jsp").forward(request, response);
        }
    }
}
